import aesJm from "../utils/aes.js"
import util from "../utils/util.js"
var appInstance = getApp()
/**
 * AES-128 加密 
 * @param {type string} hexStr 加密前的16个字节的进制字符串  
 * @param {type array} keys 开锁器或者是锁的 keys 10进制数组
 * hexStr示例：06010101000000000000000000000000
 * keys示例：[20, 82, 47, 82, 54, 75, 63, 71, 48, 80, 65, 88, 17, 99, 45, 43]
 */
export const encryptionData = (hexStr, keys) => {
    if (keys === undefined) return console.error('encryptionData 方法keys必须传入');

    var byteKey = aesJm.CryptoJS.enc.int8array.parse(keys);
    var byteData = aesJm.CryptoJS.enc.Hex.parse(hexStr);
    var encrypt = aesJm.CryptoJS.AES.encrypt(byteData, byteKey, {
        mode: aesJm.CryptoJS.mode.ECB, // 加密模式
        padding: aesJm.CryptoJS.pad.NoPadding, //填充方式
        // iv: '', //偏移量
    });
    var encryptedStr = encrypt.ciphertext.toString();
    return encryptedStr;
}

/**
 * AES-128 解密
 */
export const decryptData = (hexStr, keys) => {
    if (keys === undefined) return console.error('decryptData 方法keys必须传入');

    var byteKey = aesJm.CryptoJS.enc.int8array.parse(keys);
    // console.log("byteKey:",byteKey)
    var byteData = aesJm.CryptoJS.enc.Hex.parse(hexStr);
    byteData = aesJm.CryptoJS.enc.Base64.stringify(byteData);
    // console.log("byteData:",byteData)

    var decrypt = aesJm.CryptoJS.AES.decrypt(byteData, byteKey, {
        mode: aesJm.CryptoJS.mode.ECB, // 加密模式
        padding: aesJm.CryptoJS.pad.NoPadding, //填充方式
        // iv: '', //偏移量
    });
    
    var decryptedStr = decrypt.toString(aesJm.CryptoJS.enc.Hex);
    // console.log("decryptedStr:",decryptedStr)
    return decryptedStr.toString();
}
// ArrayBuffer转16进度字符串hex示例
function arrayToHexString(buffer) {
    const hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return (`00${bit.toString(16)}`).slice(-2)
      }
    )
    return hexArr.join('')
}


function decryptEcgData(byteBuffer, keyStr) {
    let hexEncStr = util.arrayToHexString(byteBuffer)
    var key = keyStr
    var keyBuffer = []
    for(var i = 0; i < key.length; i++){
        let keyValue = key.charCodeAt(i);
        keyBuffer.push(keyValue)
    }

    var decCompltetStr = ""
    let unEncStr = hexEncStr.slice(0,4)
    // console.log("unEncStr:",unEncStr)
    decCompltetStr += unEncStr
    let encStr = hexEncStr.slice(4)
    // console.log("encStr:",encStr)

    let decryptNum = parseInt(encStr.length/32);
    // console.log("decryptNum:",decryptNum)
    let remainder = encStr.length % 32;
    // console.log("remainder:",remainder)

    for (let index = 0; index < decryptNum; index++) {
        let section = encStr.slice(index*32, (index+1)*32)
        // console.log("section:",section)

        let decryptSection = decryptData(section, keyBuffer)
        // console.log("decryptSection:",decryptSection)

        decCompltetStr += decryptSection
    }
    if (remainder != 0) {
        let leftStr = encStr.slice(32*decryptNum, 32*decryptNum+remainder)
        // console.log("leftStr:",leftStr)

        decCompltetStr += leftStr
    }
    // console.log(decCompltetStr)
    let buffer = new Uint8Array(util.hexStrToArray(decCompltetStr))
    return buffer
}

//解压数据
function decompression_data(inputBuffer) {
    let j = 0
    let in_len = inputBuffer.length
    console.log(in_len)
    var output = []
    for (let i = 0; i < in_len; i++) {
        const element = inputBuffer[i];
        // let pare1 = element & 128
        
        if (element & 128) {
            output[j] = element & 63
            output[j] += inputBuffer[i+1] << 6
            if (element & 64) {
                output[j] = ~output[j] + 1
            }
            i++
            j++
        }else{
            output[j] = inputBuffer[i] & 63
            if (inputBuffer[i] & 64) {
                output[j] = ~output[j] + 1
            }
            j++
        }
    }
    // console.log(j)
    // console.log(output)
    for (let k = 1; k < j; k++) {
        output[k] = output[k] + output[k-1]        
    }
    // console.log(output)

    return output
}
//计算ECG设备的电量
function caculateBatteryPrecent(voltage) {
    let voltageTable = [4100.0, 4011.2, 3912.9, 3831.0, 3774.9, 3734.4, 3688.4, 3605.3, 3560.3 , 3500.3]
    let precentTable = [100, 86, 72, 58, 43, 35, 28, 20, 10 ,1]

    var batteryPrecent = 0
    var index = -1
    for (let i = 0; i < voltageTable.length; i++) {
        if (voltage >= voltageTable[i]) {
            index = i
            break;
        }
    }
    if (index == -1) {
        return 0
    }
    if (index >= voltageTable.length) {
        return 0
    }
    if (index == 0) {
        batteryPrecent = 100
    }else{
        batteryPrecent = (voltage - voltageTable[index])/((voltageTable[index-1] - voltageTable[index])/(precentTable[index-1] -precentTable[index])) + precentTable[index]
    }

    return parseInt(batteryPrecent)
}


function analysisData(byteBuffer){
    var data_type = ""
    var valueStr = ""
    let byte1 = byteBuffer[0]
    let byte2 = byteBuffer[1]
    if (byte1 == 255 && byte2 == 254) {
        let byte3 = byteBuffer[2]
        if (byte3 == 7) {
            data_type = 'Battery'
            let batteryVoltage = parseInt((byteBuffer[5]<<8 | byteBuffer[6]));
            console.log('电量:',batteryVoltage)
            let precent = caculateBatteryPrecent(batteryVoltage)
            valueStr = String(Number(precent))
        }else if (byte3 == 10) {
            data_type = 'ACK回复'
            let replyValue = byteBuffer[3]
            let result = byteBuffer[4]
            if (result == 255) {
                valueStr = '无效指令'
            }
        }else if (byte3 == 52) {
            data_type = '设备定时状态' 
            let timeStamp = ((byteBuffer[4] << 24) & 0xFF000000) |
            ((byteBuffer[5] << 16) & 0xFF0000) |
            ((byteBuffer[6] << 8) & 0xFF00) |
            ((byteBuffer[7]) & 0xFF)
            let flashNum = (byteBuffer[12] << 8) + byteBuffer[13]
            valueStr = "时间:"+String(timeStamp) + " flash条数:"+String(flashNum)
        }else if (byte3 == 14) {
            data_type = '设备信息'
            let sample = byteBuffer[3] & 0x01;
            let sampleStr = sample == 0 ? "stop sample," : "start sample,"
            valueStr += sampleStr
            let rts = (byteBuffer[3] >> 6) & 0x01;
            if (rts == 0) {
                valueStr += "打开实时，"
            }else{
                valueStr += "关闭实时，"
            }
        }
    }else{
        data_type = 'ECG'
        if (byte1 == 70) {//0x46
            
        }else if (byte1 == 72) {//0x48
            
        }else if (byte1 == 73) {//0x49
            let decryptBuffer = decryptEcgData(byteBuffer)
            console.log("帧值:",byte2)
            if (byte2 == 0) {
                //有效数据长度
                let effectiveLength = (decryptBuffer[2] << 8) + decryptBuffer[3]
                console.log("有效长度:",effectiveLength)
                //ecg长度
                let ecgLength = (decryptBuffer[4] << 8) + decryptBuffer[5]
                console.log("ecg模块长度:",ecgLength)
                let effectiveData = new Uint8Array(byteBuffer.slice(6))
                console.log(effectiveData)
                if (byteBuffer.length >= effectiveLength + 4 ) {
                    console.log("够了")
                }else{
                    console.log("返回")
                    // return {"type":"ECG","value":effectiveData}
                }
            }else if (byte2 == 1) {
                console.log("第二帧")
                // var incompleteBuffer = lastBuffer
                // console.log("incompleteBuffer:",incompleteBuffer)
                // let eff = decryptBuffer.slice(2)
                // incompleteBuffer.push.apply(incompleteBuffer, eff)
                // console.log(incompleteBuffer)
                
            }
            


        }else if (byte1 == 74) {//0x50
            
        }
        
    }
    return {"type":data_type,"value":valueStr}
}

module.exports = {
    analysisData,
    caculateBatteryPrecent,
    decryptEcgData,
    decompression_data,
}